//
//  ViewController.swift
//  YLPaymentDemo
//
//  Created by changhe on 2025/4/12.
//

import UIKit
import StoreKit

class ViewController: UIViewController {
    
    // MARK: - 属性
    
    // UI组件
    private lazy var productTableView: UITableView = {
        let tableView = UITableView()
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "ProductCell")
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    private let statusLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.numberOfLines = 0
        label.text = "准备加载商品..."
        return label
    }()
    
    private let loadingIndicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(style: .medium)
        indicator.hidesWhenStopped = true
        return indicator
    }()
    
    // 数据
    private var products: [Any] = []
    private let productIds = ["com.example.premium", "com.example.coins100"]
    
    // 通过YLPaymentService访问支付管理器
    private var paymentManager: YLPaymentManager {
        return YLPaymentService.shared.paymentManager
    }
    
    // 验证器
    private lazy var validator: YLTransactionValidator = {
        return YLValidatorTransaction()
    }()
 
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        fetchProducts()
    }
    
    // MARK: - UI设置
    
    private func setupUI() {
        view.backgroundColor = .white
        title = "支付演示"

        // 添加状态标签
        view.addSubview(statusLabel)
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            statusLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20)
        ])
        
        // 添加加载指示器
        view.addSubview(loadingIndicator)
        loadingIndicator.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            loadingIndicator.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 10),
            loadingIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
        
        // 添加产品列表
        view.addSubview(productTableView)
        productTableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            productTableView.topAnchor.constraint(equalTo: loadingIndicator.bottomAnchor, constant: 20),
            productTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            productTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            productTableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    }
    
    // MARK: - 支付相关方法
    
    // 获取产品信息
    private func fetchProducts() {
        loadingIndicator.startAnimating()
        statusLabel.text = "正在加载商品..."
        
        paymentManager.fetchProducts(productIds: productIds) { [weak self] result in
            DispatchQueue.main.async {
                self?.loadingIndicator.stopAnimating()
                
                switch result {
                case .success(let products):
                    guard !products.isEmpty else {
                        self?.statusLabel.text = "没有找到商品"
                        return
                    }
                    
                    self?.products = products
                    self?.productTableView.reloadData()
                    self?.statusLabel.text = "已加载 \(products.count) 个商品"
                    
                case .failure(let error):
                    self?.statusLabel.text = "加载商品失败: \(error.localizedDescription)"
                }
            }
        }
    }
    
    // 购买产品
    private func purchaseProduct(at index: Int) {
        guard index < products.count else { return }
        
        let product = products[index]
        
        // 生成订单号 - 使用时间戳和随机数
        let timestamp = Int(Date().timeIntervalSince1970)
        let random = Int.random(in: 0...999999)
        let orderId = String(format: "%016x%016x", timestamp, random)
        
        loadingIndicator.startAnimating()
        statusLabel.text = "正在购买商品..."
        
        // 使用PaymentService进行支付
        if let skProduct = product as? SKProduct {
            let productId = skProduct.productIdentifier
            
            YLPaymentService.shared.payIAP(
                productId: productId,
                orderId: orderId,
                validator: validator
            ) { [weak self] result in
                DispatchQueue.main.async {
                    self?.loadingIndicator.stopAnimating()
                    
                    switch result {
                    case .success(let data):
                        self?.statusLabel.text = "购买成功!\n交易ID: \(data.transactionId)"
                        self?.showAlert(
                            title: "购买成功",
                            message: "商品: \(data.productId)\n订单: \(data.orderId)"
                        )
                        
                    case .failure(let error):
                        self?.statusLabel.text = "购买失败: \(error)"
                        self?.showAlert(title: "购买失败", message: "\(error)")
                    @unknown default:
                        self?.statusLabel.text = "购买结果未知"
                        self?.showAlert(title: "未知状态", message: "支付过程发生未知状态")
                    }
                }
            }
        } else {
            loadingIndicator.stopAnimating()
            statusLabel.text = "商品格式不正确"
        }
    }
    
    // 显示提示框
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
    
    // URL处理方法
    func handleURL(_ url: URL) {
        // 处理从外部应用返回的URL
        print("处理URL: \(url)")
    }
}

// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return products.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell", for: indexPath)
        
        if let product = products[indexPath.row] as? SKProduct {
            let priceFormatter = NumberFormatter()
            priceFormatter.numberStyle = .currency
            priceFormatter.locale = product.priceLocale
            
            let priceString = priceFormatter.string(from: product.price) ?? "\(product.price)"
            cell.textLabel?.text = "\(product.localizedTitle) - \(priceString)"
        } else {
            cell.textLabel?.text = "未知商品"
        }
        
        cell.accessoryType = .disclosureIndicator
        return cell
    }
}

// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        // 弹出确认框
        let alert = UIAlertController(
            title: "确认购买",
            message: "您确定要购买此商品吗?",
            preferredStyle: .alert
        )
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "购买", style: .default) { [weak self] _ in
            self?.purchaseProduct(at: indexPath.row)
        })
        
        present(alert, animated: true)
    }
}

// MARK: - SceneDelegate扩展 - URL处理

// 添加此扩展到SceneDelegate.swift文件中
/*
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else { return }
    
    // 让主控制器处理URL
    if let navController = window?.rootViewController as? UINavigationController,
       let viewController = navController.viewControllers.first as? ViewController {
        viewController.handleURL(url)
    }
}
*/


